package com.shujiaotong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shujiaotong.common.R;
import com.shujiaotong.mapper.UserCardMapper;
import com.shujiaotong.mapper.UserMapper;
import com.shujiaotong.pojo.Card;
import com.shujiaotong.mapper.CardMapper;
import com.shujiaotong.pojo.User;
import com.shujiaotong.pojo.UserCard;
import com.shujiaotong.service.ICardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shujiaotong.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-20
 */
@Service
public class CardServiceImpl extends ServiceImpl<CardMapper, Card> implements ICardService {



    @Autowired
    private UserCardMapper userCardMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public R getUserCardsByUserid(Long id) {
        // 使用 cardId 查询 userCard 表中所有匹配的 userId
        LambdaQueryWrapper<UserCard> qw = new LambdaQueryWrapper<>();
        qw.eq(UserCard::getCardId, id);
        List<UserCard> userCards = userCardMapper.selectList(qw);

        // 提取所有的 userId
        List<Long> userIds = userCards.stream()
                .map(UserCard::getUserId)
                .collect(Collectors.toList());

        List<User> users = userMapper.selectBatchIds(userIds);
//        把usercard的type覆盖查询出来的user的type，并且在users里面加入usercard表的count
        for (UserCard userCard : userCards) {
            for (User user : users) {
                if (userCard.getUserId().equals(user.getId())) {
                    user.setType(userCard.getType());
                    user.setCount(userCard.getCount());
                }
            }
        }
        return R.success(users);
    }
}
